package com.itstyle.quartz.service.impl;

import com.itstyle.quartz.dynamicquery.DynamicQuery;
import com.itstyle.quartz.entity.PageBean;
import com.itstyle.quartz.entity.Result;
import com.itstyle.quartz.entity.Userinfo;
import com.itstyle.quartz.service.IUserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service("UserinfoImpl")
public class UserinfoImpl implements IUserinfoService {


    @Autowired
    private DynamicQuery dynamicQuery;

    @Override
    @Transactional(readOnly = true)
    public Result listUserinfo(Integer pageNo, Integer pageSize) {
        String countSql = "SELECT COUNT(*) FROM userinfo";
        Long totalCount = dynamicQuery.nativeQueryCount(countSql);
        PageBean<Userinfo> data = new PageBean<>();
        if (totalCount > 0) {
            StringBuffer nativeSql = new StringBuffer();
            nativeSql.append("SELECT * FROM userinfo");
            Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
            List<Userinfo> list = dynamicQuery.nativeQueryPagingList(Userinfo.class, pageable, nativeSql.toString());
            data = new PageBean<>(list, totalCount);
        }
        return Result.ok(data);
    }

    @Override
    public List<Userinfo> listUser() {

        String nativeSql = "SELECT * FROM userinfo";
        Pageable pageable = PageRequest.of(0, 10);
        List<Userinfo> list = dynamicQuery.nativeQueryPagingList(Userinfo.class, pageable, nativeSql);
        return list;
    }

    @Override
    @Transactional
    public Result save(Userinfo userinfo) {
        dynamicQuery.save(userinfo);
        return Result.ok();
    }

    @Override
    @Transactional
    public Result delete(Userinfo userinfo) {
        dynamicQuery.delete(Userinfo.class, userinfo.getUserId());
        return Result.ok();
    }

    @Override
    @Transactional
    public Result update(Userinfo userinfo) {
        dynamicQuery.update(userinfo);
        return Result.ok();
    }
}
